package com.zl.cms.dao;

import com.zl.basic.dao.BaseDao;
import com.zl.basic.model.Pager;
import com.zl.cms.model.Attachment;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-3-7 Time: 下午9:20
 */
@Repository("attachmentDao")
public class AttachmentDao extends BaseDao<Attachment> implements IAttachmentDao {


  private String getAttachmentSelect() {
    return "select new Attachment(a.id,a.newName,a.oldName,a.suffix,a.type,a.size,a.indexPic,a.img,a.attch,a.createDate,a.topic.id)";
  }

  @Override
  public Pager<Attachment> findNoUseAttachment() {
    String hql = "select a from Attachment a where a.topic is null";
    return this.find(hql);
  }

  @Override
  public void clearNoUseAttachment() {
    String hql = "delete Attachment a where a.topic is null";

    this.updateByHql(hql);

  }

  @Override
  public void deleteByTopic(Integer tid) {
    String hql = "delete from Attachment  a where a.topic.id= ? ";
    this.updateByHql(hql, tid);

  }

  @Override
  public List<Attachment> listByTopic(Integer tid) {
    String hql = "select a  from Attachment a where a.topic.id = ?";
    return this.list(hql, tid);
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<Attachment> listIndexPic(Integer num) {
    String hql =
        getAttachmentSelect() + " from Attachment a where a.indexPic = ? and a.topic.status = 1";
    // setParameter(0,1) 0代表第一个问号，值是1
    return this.getSession().createQuery(hql).setParameter(0, 1).setFirstResult(0)
        .setMaxResults(num).list();
  }

  @Override
  public Pager<Attachment> findChannelPic(Integer cid) {
    // 文章状态是1 ，并且cid栏目里的文章的图片，，
    String hql =
        getAttachmentSelect() + " from Attachment a where a.topic.status=1 and "
            + "a.topic.channel.id = ?  and a.id = a.topic.channelPicId";
    return this.find(hql, cid);
  }

  @Override
  public List<Attachment> listAttachByTopic(Integer tid) {
    String hql = getAttachmentSelect() + " from Attachment a where a.topic.id=? and a.attch = 1 ";
    return this.list(hql, tid);
  }
}
